//
//  ZXCheckAppItunesVersionManager.m
//  CollagePicture
//
//  Created by simon on 16/11/18.
//  Copyright © 2016年 sina. All rights reserved.
//

#import "ZXCheckAppItunesVersionManager.h"
#import "ZXCheckAppVersionHttpError.h"
#import <YYModel/YYModel.h>

typedef void (^ErrorBlock)(NSError* error);


@interface ZXCheckAppItunesVersionManager ()

@end


@implementation ZXCheckAppItunesVersionManager


- (void)dealloc{
    
}


+ (void)checkAppStoreNewVersionWithAppleID:(NSString *)appleID
                                   success:(nullable void(^)(BOOL isHaveNewVersion,CAIItunesModel *itunesModel))success
                                   failure:(nullable void(^)(NSError *error))failure
{
    NSString *url = [self appStoreAppInfomationURLForApplicationIdentifier:appleID];
    [self checkAppStoreNewVersionWithUrl:url success:success failure:failure];
}

+ (void)checkAppStoreNewVersionWithUrl:(NSString *)url
                               success:(nullable void(^)(BOOL isHaveNewVersion,CAIItunesModel *itunesModel))success
                               failure:(nullable void(^)(NSError *error))failure
{
    [self requestItunesWithUrl:url success:success failure:failure];
}

// itunes应用信息请求检查及本地比较,网络报错也返回可更新
+ (void)requestItunesWithUrl:(NSString *)url
                     success:(nullable void(^)(BOOL isHaveNewVersion,CAIItunesModel *itunesModel))success
                     failure:(nullable void(^)(NSError* error))failure
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.timeoutIntervalForRequest = 20.f;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDataTask *task =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            BOOL isHaveNewVersion = NO;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSNumber *resultCount = [dic objectForKey:@"resultCount"];
            if (!resultCount || [resultCount integerValue] == 0)
            {
                NSString *message = [dic objectForKey:@"errorMessage"];
                NSString *errorMessage = message?message:@"没有找到这个应用,请检查";
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSError *error = [ZXCheckAppVersionHttpError customErrorWithMsg:errorMessage  errorCode:100 userInfoErrorCode:nil];
                    if (failure) {
                        failure(error);
                    }
                });
                return;
            }
            NSString *appStoreVersion = nil;
            NSArray *resultsArray =[dic objectForKey:@"results"];
            CAIItunesModel *model;
            if (resultsArray && resultsArray.count > 0) {
                NSDictionary *releaseInfo = [resultsArray firstObject];
                appStoreVersion = [releaseInfo objectForKey:@"version"];
                model = [CAIItunesModel yy_modelWithJSON:releaseInfo];
            }
            isHaveNewVersion = [ZXCheckAppItunesVersionManager isHaveNewVersionWithVersionCompare:appStoreVersion];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    success(isHaveNewVersion,model);
                }
            });
            return;
        }
        if (error) {
            NSString *msg = [ZXCheckAppVersionHttpError errorMsgWithHttpConnectErrorCode:error.code];
            error = [ZXCheckAppVersionHttpError customErrorWithMsg:msg errorCode:error.code userInfoErrorCode:nil];
            if (failure) {
                failure(error);
            }
        }
    }];
    [task resume];
}





#pragma mark - 公用方法



+ (BOOL)isBlankString:(nullable NSString *)string{
    
    if (!string || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
    {
        return YES;
    }
    return NO;
}

+ (NSString *)appStoreAppInfomationURLForApplicationIdentifier:(NSString *)appId
{
    NSString *lookup = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",appId];
    return lookup;
}

#pragma mark-Version比较

//检查是否有新版本
+ (BOOL)isHaveNewVersionWithVersionCompare:(NSString *)itunesVersion
{
    if ([self isBlankString:itunesVersion]) {
        return NO;
    }
    NSString *currentVersion =  [[NSBundle mainBundle]objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if ([itunesVersion compare:currentVersion options:NSNumericSearch] ==NSOrderedDescending)
    {
        return YES;
    }
    return NO;
}

@end
